"""Run some games in some scenarios simulating network games.

To test your agent, the major modifications you need to make are:
1. import your own agent class
2. instantiate your agent and its opponent

The code looks like:

from your_folder.your_file import YourAgent

omega = YourAgent()
gamma = # opponent agent maybe DemoAgent, YourAgent or some agent else
"""
import time
from multiprocessing import Process

from core.service.client import Client
from core.service.room import TestRoom
from examples.demo_agent import DemoAgent
from myAI.my_agent import myAgent
# from my_ai.my_agent import MyAgent as lm_agent
TEAM, CAPTAIN, CODE = 'LGD.DK', '程恺', '0ce943'
RESET_TIME_OF_YOUR_AGENT = 5
# SCENARIOS = [2010131194, 2010211129, 2010441253]  # all scenarios to play
SCENARIOS = [2030111194]
NUM_GAMES = 2  # number of games in each scenario


def run_client_in_another_process(code, agent):
    client = Client(host='localhost', port=5672, code=code, team=TEAM, captain=CAPTAIN, agent=agent)
    client.run()


def main():
    # instantiate two agents, replace with your agent here
    # alpha = DemoAgent()
    alpha = myAgent()
    # alpha = lm_agent()
    beta = DemoAgent()
    # beta = myAgent()
    # beta = lm_agent()
    # run them in two separate processes
    alpha_process = Process(target=run_client_in_another_process, args=('alpha', alpha), daemon=False)
    alpha_process.start()
    beta_process = Process(target=run_client_in_another_process, args=('beta', beta), daemon=False)
    beta_process.start()
    print('Both clients are running.')

    for scenario in SCENARIOS:
        for i in range(NUM_GAMES):
            begin = time.time()
            game_id = f'{time.strftime("%Y-%m-%d-%H-%M-%S")}_{scenario}_{i}'

            # instantiate a game room， let alpha play as red and beta as blue
            room = TestRoom(team=TEAM, captain=CAPTAIN, code=CODE, game_id=game_id, scenario=scenario,
                            red='alpha', blue='beta')
            print('TestRoom is ready.')
            # start the game with speedup ratio of 5, it may run for a few minutes
            room.run()

            # wait for your agent to reset
            time.sleep(RESET_TIME_OF_YOUR_AGENT)
            print(f'Total time of {game_id}: {time.time() - begin:.3f}s')
        print(f'Finish scenario: {scenario}.')
    print('Finish all games.')
    if alpha_process.is_alive():
        alpha_process.terminate()
    if beta_process.is_alive():
        alpha_process.terminate()

if __name__ == '__main__':
    main()
